﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using System.Xml;
using System.Data;

namespace SharePointListSync.Actions.Controls
{
    public partial class ACconnMgr : UserControl
    {
        public delegate void ProcessDelegate();
        
        public ACconnMgr()
        {
            InitializeComponent();
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            Globals.ThisWorkbook.mACBody.mACListSync.Visible = false;
            Globals.ThisWorkbook.mACBody.mACListSelector.Visible = true;
            Globals.ThisWorkbook.mACBody.mACconnMgr.Visible = false;
        }        

        #region Get All List - Btn Go
        private void btnGo_Click(object sender, EventArgs e)
        {

            //connect to the site and find lists that are instances of the project template
            if (!ConnectionManager.isOnline())
            {
                MessageBox.Show("You need an internet connection add new lists.");
                return;
            }
            if (string.IsNullOrEmpty(txtsiteURL.Text))
            {
                MessageBox.Show("Enter the Site URL");
                return;
            }

            Globals.ThisWorkbook.ActionsPane.UseWaitCursor = true;

            WSlists.Lists listservice = new WSlists.Lists();
            listservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
            try
            {
                listservice.Url = txtsiteURL.Text.Trim() + "/_vti_bin/Lists.asmx";
            }
            catch (Exception ex)
            {
                MessageBox.Show("please Check the URL");
            }
            listservice.GetListCollectionCompleted += new WSlists.GetListCollectionCompletedEventHandler(listservice_GetListCollectionCompleted);
            listservice.GetListCollectionAsync();


        }

        void listservice_GetListCollectionCompleted(object sender, WSlists.GetListCollectionCompletedEventArgs e)
        {
            if (e == null || e.Error != null)
            {
                MessageBox.Show("please enter a valid Site URL we are not able to get any list ");

            }
            else
            {
                XmlNode result = e.Result;
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(result.OuterXml);
                XmlNamespaceManager xmlnamespace = new XmlNamespaceManager(xdoc.NameTable);
                xmlnamespace.AddNamespace(Globals.ThisWorkbook.SharePointNamespacePrefix, Globals.ThisWorkbook.SharePointNamespaceUri);


                //XmlNodeList projLibNode = xdoc.SelectNodes("//sp:List[@ServerTemplate='1001']", xmlnamespace);
                int i = 0;
                XmlNodeList projLibNode = xdoc.SelectNodes("//sp:List[@Hidden='False' and @AllowDeletion='True']", xmlnamespace);
                populatetProductList(projLibNode, ref i);

            }
        }

        private void populatetProductList(XmlNodeList projLibNode, ref int i)
        {
            if (projLibNode == null || projLibNode.Count == 0)
            {
                MessageBox.Show("No lists of type Projects were found in the site");
                return;
            }
            else
            {
                //foundLists.Rows.Clear();

                // set the dropdownlist 
                foreach (XmlNode eachnode in projLibNode)
                {
                    SharePointListDetails.TempSpConnectionRow listrow = Globals.ThisWorkbook.DSlists.TempSpConnection.NewTempSpConnectionRow();
                    listrow.ListName = eachnode.Attributes["Title"].InnerText;
                    listrow.WebURL = txtsiteURL.Text.Trim().Trim('/');
                    listrow.ListID = eachnode.Attributes["ID"].InnerText;
                    listrow.WebID = eachnode.Attributes["WebId"].InnerText;
                    Globals.ThisWorkbook.DSlists.TempSpConnection.Rows.Add(listrow);
                    i++;
                }
                Globals.ThisWorkbook.DSlists.TempSpConnection.AcceptChanges();
            }


            ProcessDelegate pre = new ProcessDelegate(populateCombobox);
            this.Invoke(pre);
        }

        private void populateCombobox()
        {
            cbbLists.DataSource = Globals.ThisWorkbook.DSlists.TempSpConnection;
            cbbLists.DisplayMember = "ListName";
            cbbLists.ValueMember = "ListID";

            Globals.ThisWorkbook.ActionsPane.UseWaitCursor = false;
        }

        private void textBox1_MouseClick(object sender, MouseEventArgs e)
        {
            txtsiteURL.Text = "";
            txtsiteURL.ForeColor = System.Drawing.Color.Black;
        }

        #endregion

        #region Add selected List to Connection
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            DataRowView dataview = cbbLists.SelectedItem as DataRowView;
            SharePointListDetails.TempSpConnectionRow templistrow = dataview.Row as SharePointListDetails.TempSpConnectionRow;

            if (txtConnName.Text == null)
            {
                MessageBox.Show("please enter a valid Connection Name");
                return;
            }
            else
            {
                SharePointListDetails.SPConnectionsRow listrow = Globals.ThisWorkbook.DSlists.SPConnections.NewSPConnectionsRow();


                if (!Globals.ThisWorkbook.DSlists.SPConnections.Rows.Contains(templistrow.ListID))
                {
                    listrow.ConnectionName = txtConnName.Text.Trim();
                    listrow.WebURL = templistrow.WebURL;
                    listrow.ListName = templistrow.ListName;
                    listrow.ListID = templistrow.ListID;
                    listrow.WebID = templistrow.WebID;


                    Globals.ThisWorkbook.DSlists.SPConnections.Rows.Add(listrow);
                    Globals.ThisWorkbook.DSlists.SPConnections.AcceptChanges();

                    checkedListBox1.Items.Add(listrow.ConnectionName, false);
                }
                else
                {
                    MessageBox.Show(" this List is already added");
                }
            }

        }

        private void cbbLists_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtConnName.Text = "";
        }

        #endregion

        #region Remove selected List form  Connection
        private void BtnRemove_Click(object sender, EventArgs e)
        {
            CheckedListBox.CheckedItemCollection allchecked = checkedListBox1.CheckedItems;

            for (int j = 0; j < allchecked.Count; j++)
            {
                string connectionName = allchecked[j].ToString();

                for (int i = 0; i < Globals.ThisWorkbook.DSlists.SPConnections.Rows.Count; i++)
                {
                    SharePointListDetails.SPConnectionsRow selectrow = (SharePointListDetails.SPConnectionsRow)Globals.ThisWorkbook.DSlists.SPConnections.Rows[i];
                    if (selectrow.ConnectionName == connectionName)
                    {
                        Globals.ThisWorkbook.DSlists.SPConnections.Rows.Remove(selectrow);
                        checkedListBox1.Items.Remove(connectionName);
                    }
                }

            }
            Globals.ThisWorkbook.DSlists.SPConnections.AcceptChanges();
        } 
        #endregion
        
        #region Redundant Code 
        //private void populateCheckedListBox()
        //{

        //    checkedListBox1.Items.Clear();
        //    foreach (SharePointListDetails.SPConnectionsRow eachrow in Globals.ThisWorkbook.DSlists.SPConnections.Rows)
        //    {
        //        checkedListBox1.Items.Add(eachrow.ConnectionName, false);

        //    }
        //} 
        #endregion

    }
}
